<template>
	<view class="login-container">
		<view class="login-form">
			<uni-forms ref="loginForm" :rules="rules" :modelValue="formData">
				<uni-forms-item label="用户名" name="username">
					<uni-easyinput
						v-model="formData.username"
						placeholder="请输入用户名"
					/>
				</uni-forms-item>
				<uni-forms-item label="密码" name="password">
					<uni-easyinput
						v-model="formData.password"
						type="password"
						placeholder="请输入密码"
					/>
				</uni-forms-item>
				<button type="primary" class="login-btn" @click="handleLogin">登录</button>
			</uni-forms>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { login } from '@/api/login'

const loginForm = ref(null)

const formData = ref({
	username: '',
	password: ''
})

// 表单验证规则
const rules = {
	username: {
		rules: [{
			required: true,
			errorMessage: '请输入用户名'
		}]
	},
	password: {
		rules: [{
			required: true,
			errorMessage: '请输入密码'
		}]
	}
}

const handleLogin = async () => {
	try {
		const valid = await loginForm.value.validate()
		if (!valid) return
		
		// 显示加载提示
		uni.showLoading({
			title: '登录中...'
		})
		
		// 打印发送的数据
		console.log('发送登录请求的数据：', {
			username: formData.value.username,
			password: formData.value.password
		})
		
		const res = await login({
			username: formData.value.username,
			password: formData.value.password
		})
		
		// 打印返回的数据
		console.log('登录响应：', res)
		// 关闭加载提示
		uni.hideLoading()
		
		if (res.code === 200) {
			// 存储token
			uni.setStorageSync('token', res.data.token)
			uni.setStorageSync('username',res.data.username)
			uni.setStorageSync('userId',res.data.userId)
			// 显示成功提示
			uni.showToast({
				title: '登录成功',
				icon: 'success'
			})
			
			// 跳转到首页
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}, 1500)
		} else {
			uni.showToast({
				title: res.message || '登录失败',
				icon: 'none'
			})
		}
	} catch (error) {
		uni.hideLoading()
		uni.showToast({
			title: '登录失败',
			icon: 'none'
		})
		console.error('登录错误：', error)
	}
}
</script>

<style>
.login-container {
	padding: 20px;
}

.login-form {
	margin-top: 50px;
}

.login-btn {
	margin-top: 30px;
}
</style>